import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Typography, Flex, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { transformArray } from '../../../utils/commonUtil';
import RequestTplModal from '../../Components/RequestTplModal';
import { apiBigSimulationFileFilter, apiBigSimulationFileList, apiBigSimulationFileRemove } from '../../../services/bigSimulationFile/request';
import { apiSysDictSelect } from '../../../services/common';
import { SYSCODE, CONFIG_ITEM_KEYS, DATEFORMAT, REQUEST_PAGE, RES_MODE, APPROVAL_STATUS } from '../../../utils/constant';
import DeleteConfirm from '../../Components/DeleteConfirm';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import RequestStatus from '../../Components/RequestStatus';

const { Title } = Typography;
const BigSimulationFile = () => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { BU, MODULE } = CONFIG_ITEM_KEYS;
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [buList, setBuList] = useState([]);
  const [projectList, setProjectList] = useState([]);
  const [requesterList, setRequesterList] = useState([]);
  const [statusList, setStatus] = useState([]);
  const [newModalVisible, setNewModalVisible] = useState(false);

  // mock permission
  const isCampAdmin = true;
  const isBuPRPD = false;
  const isBuAdmin = false;
  const isBuTester = true;


  const detailClickHandle = (record, type) => {
    navigate('/bigSimulationFile/details', {
      state: {
        bigFileProjectId: record.bigFileProjectId,
        editMode: type,
      }
    });
  };
  const deleteClickHandle = (record) => {
    DeleteConfirm({
      t,
      onOk () {
        apiBigSimulationFileRemove({ bigFileProjectId: record.bigFileProjectId }).then((res) => {
          if (res?.data?.code === 200) {
            message.success(t('common.deleteSuccess'));
            queryList();
          }
        });
      }
    });
  };
  const columns = [
    {
      title: t('common.bu'),
      dataIndex: 'buType',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.project'),
      dataIndex: 'projectName',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.templateName'),
      dataIndex: 'templateName',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.requester'),
      dataIndex: 'createdBy',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.createdTime'),
      dataIndex: 'createdTime',
      width: 100,
      align: 'center',
      render: (_, record) => (
        <span>{dayjs(record.createdTime).format(DATEFORMAT)}</span>
      )
    },
    {
      title: t('common.status'),
      dataIndex: 'requestStatus',
      width: 100,
      align: 'center',
      render: (_, record) => (
        <RequestStatus status={record?.requestStatus} />
      )
    },
    {
      title: ' ',
      dataIndex: 'operate',
      width: 300,
      align: 'center',
      render: (_, record) => (
        <Space size={2}>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, RES_MODE.VIEW)}>{t('common.view')}</Button>
          {
            //可填写测试数据
            (isCampAdmin || isBuPRPD || isBuAdmin || isBuTester) && record?.requestStatus === APPROVED ?
              <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, RES_MODE.TESTEREDIT)}>{t('common.edit')}</Button>
              :
              //可重新编辑
              (isCampAdmin || isBuPRPD || isBuAdmin) ?
                <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, RES_MODE.EDIT)} disabled={record?.requestStatus !== DRAFT && record?.requestStatus !== REJECTED}>{t('common.edit')}</Button>
                :
                <></>
          }
          {
            (isCampAdmin || isBuPRPD || isBuAdmin) &&
            <Button type="link" className='red' size='small' onClick={() => deleteClickHandle(record)} disabled={record?.requestStatus !== DRAFT && record?.requestStatus !== REJECTED}>{t('common.delete')}</Button>
          }
        </Space>
      ),
    }
  ];
  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes || [],
      projectNames: formData?.projectNames || [],
      requesters: formData?.requesters || [],
      requestStatus: formData?.requestStatus || [],
    };
    return params;
  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiBigSimulationFileList(params).then((res) => {
      setDataList(res?.data?.data?.items);
      setTotalPage(res?.data?.data?.total);
    });
  };

  // 调用下拉框api
  const apiSelectAsync = async () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [BU]
    };
    const { data } = await apiSysDictSelect(params);
    setBuList(transformArray(data?.data?.[BU]));

    apiBigSimulationFileFilter().then((res) => {
      if (res?.data?.code === 200) {
        setProjectList(transformArray(res?.data?.data?.projectName));
        setStatus(transformArray(res?.data?.data?.requestStatus));
        setRequesterList(transformArray(res?.data?.data?.requester));
      }
    });
  };
  const newTplClick = () => {
    setNewModalVisible(true);
  };
  // initiate click callback
  const newTplInitiateCallbackFn = (data) => {
    setNewModalVisible(false);
  };
  useEffect(() => {
    // 正式数据
    queryList();
    // 调用下拉框api
    apiSelectAsync();
  }, [])

  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('common.requestList')}</Title>
          <Button type='primary' onClick={() => { newTplClick() }}>{t('common.new')}</Button>
        </Flex>
      </div>
      <div className='page-content-wrap'>
        <Form form={form} className='filter-wrap'>
          <Flex align='center' gap="middle">
            <Form.Item name="buTypes"
              label={t('common.bu')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buList} />
            </Form.Item>
            <Form.Item name="projectNames"
              label={t('common.project')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={projectList} />
            </Form.Item>
            <Form.Item name="requesters"
              label={t('common.requester')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={requesterList} />
            </Form.Item>
            <Form.Item name="requestStatus"
              label={t('common.status')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={statusList} />
            </Form.Item>
            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />
          </Flex>
        </Form>
        <Table
          columns={columns}
          dataSource={dataList}
          size='small'
          rowKey='bigFileProjectId'
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return `Total ${total} items`;
            },
          }}
        />
      </div>
      {
        newModalVisible &&
        <RequestTplModal
          newModalVisible={newModalVisible}
          setNewModalVisible={setNewModalVisible}
          newTplInitiateCallbackFn={newTplInitiateCallbackFn}
          moduleConfig={REQUEST_PAGE['Big Simulation File']}
        />
      }

    </>
  )
};

export default BigSimulationFile;
